/**
 * 
 */
package cn.terrence.myoauth2.server.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;

/**
 * @author cuihua022
 * 授权服务Servlet
 */
public class AuthCodeBuilderServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -968344824551817835L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String redirectUri = "";
		OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
		try {
			OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
			redirectUri = oauthRequest.getRedirectURI();
			OAuthResponse resp = OAuthASResponse
		             .authorizationResponse(request,HttpServletResponse.SC_FOUND)
		             .setCode(oauthIssuerImpl.authorizationCode())
		             .location(redirectUri)
		             .buildQueryMessage();
		         response.sendRedirect(resp.getLocationUri());
		} catch (OAuthSystemException e) {
			e.printStackTrace();
		} catch (OAuthProblemException ex) {
			try {
				OAuthResponse resp = OAuthASResponse
				         		     .errorResponse(HttpServletResponse.SC_FOUND)
				                     .error(ex)
				                     .location(redirectUri)
				                     .buildQueryMessage();
				response.sendRedirect(resp.getLocationUri());
			} catch (OAuthSystemException e) {
				e.printStackTrace();
			}        
		}
	}
}
